import React, { useEffect, useRef, useState } from 'react';
import { Switch, Modal, Button, Form, Popconfirm, message } from 'antd';
import { connect, useRequest } from "umi";
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { doFetch } from '@/utils/doFetch';


let Child = (props) => {
    const { global, dispatch } = props,
        defaultFields = {
            "mailNo": {
                "value": null,
                "type": "input",
                "title": "邮箱",
                "name": [
                    "mailNo"
                ],
                "required": true
            },
            "accountName": {
                "value": null,
                "type": "input",
                "title": "用户名",
                "name": [
                    "accountName"
                ],
                "required": true
            },
            "userName": {
                "value": null,
                "type": "input",
                "title": "客服名称",
                "name": [
                    "userName"
                ],
                "required": true
            },
            "password": {
                "value": null,
                "type": "password",
                "title": "密码",
                "name": [
                    "password"
                ],
                "required": true
            },
            "confirmpassword": {
                "value": null,
                "type": "password",
                "title": "确认密码",
                "name": [
                    "confirmpassword"
                ],
                "required": true,
                checkConfirm: (rule, value) => {
                    if (
                        value &&
                        value !== formRef.getFieldValue('password')
                    ) {
                        return Promise.reject('2次密码不一致！');
                    } else {
                        return Promise.resolve();
                    }
                },
            },
            "telephone": {
                "value": null,
                "type": "input",
                "title": "手机号码",
                "name": [
                    "telephone"
                ],
                "required": false
            },
            "genderType": {
                "value": null,
                "type": "radio",
                "title": "性别",
                "name": [
                    "genderType"
                ],
                "required": false,
                "options": [
                    {
                        "label": "先生",
                        "value": 1
                    },
                    {
                        "label": "女士",
                        "value": 2
                    }
                ]
            },
            "remark": {
                "value": null,
                "type": "textarea",
                "title": "备注",
                "name": [
                    "remark"
                ],
                "required": false,
                "col": {
                    "span": 24
                }
            }
        };
    const actionRef = useRef();
    const [vs, cvs] = useState(false),//表单显/隐
        [fields, cf] = useState(defaultFields),
        [iftype, ciftype] = useState({}),
        [formRef] = Form.useForm();

    const { run, loading } = useRequest(doFetch, {
        manual: true,
        formatResult: (res) => res,
        onSuccess: (result, params) => {
            message.destroy()
            if (result.code == "0000") {
                message.success(result.msg)
                actionRef.current.reload();
                cvs(false);
            } else {
                message.error(result.msg)
            }
        }
    })

    const columns = [
        {
            "title": "登录名",
            "dataIndex": "accountName",
            "key": "accountName",
            "search": false
        },
        {
            "title": "客服名称",
            "dataIndex": "userName",
            "key": "userName",
            "search": false
        },
        {
            "title": "性别",
            "dataIndex": "genderName",
            "key": "genderName",
            "search": false
        },
        {
            "title": "邮箱",
            "dataIndex": "mailNo",
            "key": "mailNo",
            "search": false
        },
        {
            "title": "手机",
            "dataIndex": "telephone",
            "key": "telephone",
            "search": false
        },
        {
            "title": "状态",
            "dataIndex": "statusName",
            "key": "statusName",
            "search": false,
            render: (text, record) => {
                return <Switch checkedChildren={record.statusName} unCheckedChildren={record.statusName} checked={record.status == 1} onChange={(val) => {
                    run({ url: "/ngic-promote-epauth/epUser/disabledSon", params: { id: record.id, status: val ? 1 : 2 } });
                }}></Switch>
            }
        },
        {
            "title": "备注",
            "dataIndex": "remark",
            "key": "remark",
            "search": false
        },
        {
            "title": "操作",
            "valueType": "option",
            "width": 160,
            "render": (text, row, _, action) => extraAction(text, row, _, action)
        }
    ];

    function extraAction(text, record, _, action) {
        return [
            <a style={{ color: "red" }} onClick={() => {
                ciftype({
                    val: "editpwd",
                    id: record.id,
                    title: "重置密码"
                })
                cf(() => {
                    return {
                        "password": {
                            "value": null,
                            "type": "password",
                            "title": "密码",
                            "name": [
                                "password"
                            ],
                            "required": true,
                            col: { span: 24 }
                        },
                        "confirmpassword": {
                            "value": null,
                            "type": "password",
                            "title": "确认密码",
                            "name": [
                                "confirmpassword"
                            ],
                            "required": true,
                            col: { span: 24 },
                            checkConfirm: (rule, value) => {
                                if (
                                    value &&
                                    value !== formRef.getFieldValue('password')
                                ) {
                                    return Promise.reject('2次密码不一致！');
                                } else {
                                    return Promise.resolve();
                                }
                            },
                        },
                    }
                });
                cvs(true);
            }}>重置密码</a>
            ,
            <a onClick={() => {
                ciftype({
                    val: "edit",
                    id: record.id,
                    title: "修改子账号"
                })
                cf(() => {
                    for (let i in defaultFields) {
                        defaultFields[i].value = record[i];
                        if (i.indexOf("password") != -1) {
                            defaultFields[i].hides = true;
                        }
                    }
                    return { ...defaultFields }
                });
                cvs(true);
            }}>
                修改
            </a>,
            <Popconfirm
                title="确认删除该子账号？"
                onConfirm={() => {
                    run({ url: "/ngic-promote-epauth/epUser/deleteSon", params: { id: record.id } });
                }}
            >
                <a style={{ color: "red" }}>删除</a>
            </Popconfirm>
        ]
    }

    let saveData = (values, fn) => {
        let newfields = JSON.parse(JSON.stringify(values));
        //新增&修改
        let difrid = iftype.val.indexOf("edit") != -1 ? { id: iftype.id } : {};
        delete newfields.confirmpassword

        run({ url: iftype.val == "editpwd" ? "/ngic-promote-epauth/epUser/resetPasswordSon" : "/ngic-promote-epauth/epUser/saveSon", params: { ...newfields, ...difrid, userType: "2" } })
    }

    let extra = (<a onClick={() => {
        cvs(true);
        cf(fields => {
            for (let i in defaultFields) {
                defaultFields[i].value = null;
                defaultFields[i].hides = false;
            }
            return { ...defaultFields }
        });
        ciftype({
            val: "add",
            title: "新增子账号"
        })
    }}>新增</a>)


    return (
        <div className="nopa autotable">
            <AutoTable
                pagetitle={props.route.name}
                pageextra={extra}
                columns={columns}
                actionRef={actionRef}
                extraparams={{ userType: "2" }}
                path="/cujin/ngic-promote-epauth/epUser/querySon"
            ></AutoTable>


            <Modal
                maskClosable={false}
                title={iftype.title}
                visible={vs}
                onCancel={() => cvs(false)}
                footer={false}
                destroyOnClose={true}
            >
                <InitForm
                    formRef={formRef}
                    fields={fields}
                    submitData={(values, fn) => {
                        saveData(values, fn)
                    }}
                    onChange={(changedValues, allValues) => {
                    }}
                    submitting={
                        loading || !vs
                    }
                >
                </InitForm>
            </Modal>
        </div>
    )
}

export default connect(({ global, loading }) => ({
    global,
    loading,
}))(Child)